/*
 * Copyright 2010 Francisco Modesto
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.googlecode.gwt.tinyaop.rebind;

import com.google.gwt.user.rebind.SourceWriter;

public class InterceptorBuilder implements Builder {
  private int method;
  private Class<?> interceptor;
  private Builder body;

  public InterceptorBuilder(int method, Class<?> interceptor, Builder body) {
    this.method = method;
    this.interceptor = interceptor;
    this.body = body;
  }
  
  @Override
  public void create(SourceWriter writer) {
    writer.println("new " + interceptor() + "().invoke(new Invocation() {");
    writer.indent();
    writer.println("@Override");
    writer.println("public final MethodDescriptor getMethod() {");
    writer.indentln("return " + method() + ";");
    writer.println("}");
    writer.println();
    writer.println("@Override");
    writer.println("public final Object getThis() {");
    writer.indentln("return _this;");
    writer.println("}");
    writer.println();
    writer.println("@Override");
    writer.println("public final Object[] getArguments() {");
    writer.indentln("return _args;");
    writer.println("}");
    writer.println();
    writer.println("@Override");
    writer.println("public final Object proceed() {");
    writeBody(writer);
    writer.println("}");
    writer.outdent();
    writer.println("});");
  }

  private String interceptor() {
    return interceptor.getCanonicalName();
  }

  private String method() {
    return "_METHOD_" + method;
  }

  private void writeBody(SourceWriter writer) {
    writer.indent();
    body.create(writer);
    writer.outdent();
  }
}
